<template>
  <div style="margin: 0 auto">
    <h1 style="text-align: center">{{ title }}</h1>
    <a-row class="calendar-content" style="margin: 0 auto; width: 100%">
      <a-col :span="24" class="calendarBox">
        <a-calendar :header-render="headerRender" :disabledDate="disabledDate" @panelChange="panelChange"
                    @select="selectDate">

          <div class="calendar-item-box" :class="{active: getListData(value).active}" slot="dateCellRender"
               slot-scope="value">
            <a-tooltip>
              <template slot="title">
                <div v-for="(subItem, subIndex) in getListData(value).list" :key="subIndex">
                  {{ subItem }}
                </div>
              </template>
              <ul class="events">
                <template v-for="(item, index) in getListData(value).list">
                  <li :key="index" v-if="index < 3">
                    <div class="cellBlockOld">
                      <span>{{ item }}</span>
                    </div>
                  </li>
                </template>
              </ul>
            </a-tooltip>
          </div>
        </a-calendar>
      </a-col>
    </a-row>
    <div class="calendar-footer" v-if="footer">
      <a-button type="primary" @click="submit">确定</a-button>
      <a-button @click="cancel">取消</a-button>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import moment from 'moment'

export default {
  name: "zh-calendar",
  components: {},
  props: {
    title: {
      type: String,
      default: ''
    },
    // 赋值数据
    data: {
      type: Array,
      default: () => []
    },
    // 是否显示底部
    footer: {
      type: Boolean,
      default: false
    },
    // 日期格式化
    formatDate: {
      type: String,
      default: 'YYYY-MM-DD'
    },
    // 是否显示日期选择框
    // datePicker: {
    //   type: Boolean,
    //   default: false
    // },
    // 禁用日期
    disabledDate: {
      type: Function
    }
  },
  watch: {
    data: {
      handler(val) {
        this.dataList = val
        // console.log('注入:', this.dataList)
      }
    }
  },
  data() {
    return {
      value: moment(new Date()),
      dataList: [],
      now: new Date(),
      selectDateValue: [],
      startDate: '',
    }
  },
  methods: {
    moment,
    headerRender({value, type, onChange, onTypeChange}) {
      const start = 0;
      const end = 12;
      const monthOptions = [];

      const current = value.clone();
      const localeData = value.localeData();
      const months = [];
      for (let i = 0; i < 12; i++) {
        current.month(i);
        months.push(localeData.monthsShort(current));
      }

      for (let index = start; index < end; index++) {
        monthOptions.push(
            <a-select-option class="month-item" key={`${index}`}>
              {months[index]}
            </a-select-option>,
        );
      }
      const month = value.month();

      const year = value.year();
      const options = [];
      for (let i = year - 10; i < year + 10; i += 1) {
        options.push(
            <a-select-option key={i} value={i} class="year-item">
              {i}
            </a-select-option>,
        );
      }
      return (
          <div style={{padding: '10px'}}>
            <a-row type="flex" justify="space-between">
              <a-col>
                <div class="calendar-operate">
                  <span>选择预约日期范围：</span>
                  <a-range-picker
                      disabled-date={this.disabledDate}
                      onChange={dates => {
                        this.onChange(dates)
                      }}/>
                  <a-popconfirm
                      title="确认重置?"
                      ok-text="是"
                      cancel-text="否"
                      onConfirm={() => {
                        this.clean()
                      }}
                  >
                    <a-button>重置</a-button>
                  </a-popconfirm>
                </div>
              </a-col>
              <a-col>
                <a-select
                    dropdownMatchSelectWidth={false}
                    class="my-year-select"
                    onChange={newYear => {
                      const now = value.clone().year(newYear);
                      onChange(now);
                    }}
                    value={String(year)}
                >
                  {options}
                </a-select>
                <a-select
                    class="my-year-select"
                    dropdownMatchSelectWidth={false}
                    value={String(month)}
                    onChange={selectedMonth => {
                      const newValue = value.clone();
                      newValue.month(parseInt(selectedMonth, 10));
                      onChange(newValue);
                    }}
                >
                  {monthOptions}
                </a-select>
                <a-radio-group onChange={e => onTypeChange(e.target.value)} value={type}>
                  <a-radio-button value="month">月</a-radio-button>
                  <a-radio-button value="year">年</a-radio-button>
                </a-radio-group>
              </a-col>
            </a-row>
          </div>
      );
    },
    panelChange(value) {
      // console.log('面板中点击、切换事件')
      // console.log(moment(value).format('YYYY-MM'))
      this.value = value
      this.$emit('panelChange', moment(value).format('YYYY-MM'))
    },
    /**
     * 选中日期事件
     */
    selectDate(value) {
      // console.log('选中日期事件')
      // console.log(value)
      let index = _.findIndex(this.dataList, item => {
        return item.date === value.format(this.formatDate)
      })
      if (index >= 0 && !this.startDate && this.dataList[index].active) {
        this.dataList[index].active = false
      } else if (index >= 0 && this.startDate && this.dataList[index].active) {
        this.startDate = ''
      } else if (this.startDate) {
        this.setDate(this.startDate, value)
        this.startDate = ''
      } else {
        this.startDate = value.format(this.formatDate)
        if (index < 0) {
          this.dataList.push({
            date: value.format(this.formatDate),
            active: true,
            list: []
          })
        } else {
          this.dataList[index].active = true
        }
      }
      this.$emit('change', this.getSelectListData())
    },
    /**
     * 范围选择正选
     * @param  {string}  start  起始日期
     * @param  {string}  end  结束日期
     */
    setDate(start, end) {
      let days = moment(end).diff(moment(start), 'days')
      // console.log(`间隔${days}天`)
      let dayIndex
      let currentDate = ''
      for (let i = 0; i <= (days >= 0 ? days : Math.abs(days - 1)); i++) {
        if (days > 0) {
          currentDate = moment(start).add(i, 'days').format(this.formatDate)
        } else {
          currentDate = moment(start).subtract(i, 'days').format(this.formatDate)
        }
        dayIndex = _.findIndex(this.dataList, item => {
          return item.date === currentDate
        })
        // console.log(`获取到：${currentDate}, ${dayIndex}`)
        if (dayIndex < 0) {
          this.dataList.push({
            date: currentDate,
            active: true,
            list: []
          })
        } else {
          this.dataList[dayIndex].active = true
        }
      }
    },
    /**
     * 清除选择
     */
    clean() {
      this.startDate = ''
      _.each(this.dataList, item => {
        item.active = false
      })
      this.$emit('change', this.getSelectListData())
    },
    cancel() {
      this.clean()
    },
    /**
     *  选择框选择日期范围
     */
    onChange(dates) {
      if (dates) {
        this.setDate(dates[0], dates[1])
        this.$emit('change', this.getSelectListData())
      }
    },
    getListData(value) {
      let listData = {};
      // 注意事项1：通过比对日期确定将每日的交易状态与日历日期匹配
      this.dataList.forEach(e => {
        // 让数组与日历日期匹配
        if (e.date === value.format(this.formatDate)) {
          listData = (e)
        }
      })
      // console.log(moment(value).format('YYYY-MM-DD') + ':', listData)
      return listData
    },
    getSelectListData() {
      this.selectDateValue = []
      this.dataList = _.orderBy(this.dataList, o => {
        return moment(o.date)
      })
      _.each(this.dataList, item => {
        if (item.active) {
          this.selectDateValue.push(item.date)
        }
      })
      return this.selectDateValue
    },
    /**
     * 确认提交
     */
    submit() {
      console.log(this.selectDateValue)
      this.$emit('confirm', this.selectDateValue)
    }
  },
  computed: {
    nowDate: function () {
      return moment(this.now).format(this.formatDate)
    },
    next: function () {
      let next;
      const nextDate = new Date(this.now - 0 + 86400000);
      next = moment(nextDate).format(this.formatDate)
      return next
    }
  },
  created() {
  },
  mounted() {
    this.dataList = this.data
  }
}
</script>

<style scoped lang="less">
// .calendar-operate {
//   text-align: left;

//   .ant-calendar-picker {
//     margin-right: 10px;
//   }
// }

// .calendar-item-box {
//   height: 100%;
// }

// .active {
//   background-color: #69c0ff;
//   color: #ffffff;
//   border-radius: 4px;
// }

// .events {
//   height: 100%;
//   margin: 0;
//   padding: 10px 0;
//   border-radius: 4px;

//   .cellBlockOld {
//     text-align: center;
//     white-space: nowrap;
//     overflow: hidden;
//     text-overflow: ellipsis;
//   }
// }

// /deep/ .ant-fullcalendar-date {
//   background: transparent !important;
// }

// .my-year-select {
//   margin-right: 1px;
//   width: 80px;
// }

// .calendar-footer {
//   text-align: right;

//   .ant-btn {
//     margin-right: 10px;
//   }
// }
</style>
